package com.zx.rbac.common.exception;

import com.zx.rbac.common.api.IResultCode;
import com.zx.rbac.common.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :xxx
 * @description:TODO
 * @date :2021/7/24 22:56
 */
@RestControllerAdvice
@Slf4j
public class BaseExceptionHandlerController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getObjectName();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String,String> resultMap = new HashMap<>();
        fieldErrors.forEach((item)->{
            log.info("参数{}校验失败，原因：{}",item.getField(),item.getDefaultMessage());
            resultMap.put(item.getField(),item.getDefaultMessage());
        });
        return Result.failed(IResultCode.VALIDATE_FAILED);
    }

    @ExceptionHandler(RRException.class)
    public Result rRExceptionHandler(RRException e){
        log.error("出现异常：{}",e.getLocalizedMessage());
        return Result.failed(e.getIResultCode());
    }

    @ExceptionHandler(Exception.class)
    public Result methodArgumentNotValidException(Exception e){
        log.error("出现异常：{}",e.getLocalizedMessage());
        return Result.failed(IResultCode.SYSTEM_ERROR);
    }

}
